<template>
  <div>
    <h1 style="text-align: center">调度处理</h1>
    <hr>
  </div>
  <el-form ref="refRestockTable" :model="restock" label-width="80px">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="申请门店:">
          <el-text>{{restock.storeName}}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="申请人:">
          <el-text>{{ restock.managerName }}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="日期:">
          <el-text>{{restock.submitTime}}</el-text>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="单据编号:">
          <el-text>{{ restock.replenishId }}</el-text>
        </el-form-item>
      </el-col>
    </el-row>


    <el-table  :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="操作" class="custom-first-column">
        <template #header>
          <el-icon><Setting /></el-icon>
        </template>
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="edit"></el-button>
          <el-button v-if="type" type="text" icon="Minus" @click="handleDelete(scope.$index)"></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="itemInformation.id" label="商品编号" align="center" />
      <el-table-column prop="itemInformation.categoryName" label="商品类别" align="center" />
      <el-table-column prop="itemInformation.productName" label="商品名称" align="center" />
      <el-table-column prop="itemInformation.manufacturer" show-overflow-tooltip label="生产地" align="center" />
      <el-table-column v-if="type" prop="quantity" label="商品数量" align="center" >
        <template #default="scope">
          <el-input-number  v-model="scope.row.quantity"  size="small" @change="handleChange(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column v-else prop="quantity" label="商品数量" align="center" />
      <el-table-column prop="supplyingStoreName" v-if="restock.status === '待审核'" label="供货门店" align="center" />
      <el-table-column prop="supplyingStoreId" v-else label="供货门店id" align="center" />
      <el-table-column prop="description" label="备注" align="center" >
        <template #default="scope">
          <el-input v-model="scope.row.description" size="small" :placeholder="scope.row.supplyingStoreName"></el-input>
        </template>
      </el-table-column>
      <el-table-column v-if="!type" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="restock.status === '待审核'" type="text" @click="getStockOptions(scope.row)">商品调度</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 按钮区域 -->
    <el-row style="text-align: right; padding-top: 30px">
      <el-col>
        <el-button type="primary" @click="mainCancel">返回</el-button>
        <el-button type="primary" v-if="restock.status === '待审核'" @click="submitMainForm">提交</el-button>
<!--        <el-button v-if="type" type="primary" @click="save">保存</el-button>-->
      </el-col>
    </el-row>
  </el-form>

  <!-- 商品列表表格 -->
  <el-dialog title="选择商品" v-model="open" heght="1000px" width="1000px" append-to-body>

    <el-table ref="multipleSelection" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="店铺名称" align="center" prop="storeName" />
      <el-table-column label="商品名称" align="center" prop="itemInformation.productName" />
      <el-table-column label="库存量" align="center" prop="stockQty" />
      <el-table-column label="库存状态" align="center" prop="stockStatus" />
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getStockOptions"
    />


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="send">加入采购列表</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>

import {getStockDetail, submitRestock, sendRestock, saveRestock, getListStock} from "@/api/restock/restock.js";
import {ElMessage} from "element-plus";


const route = useRoute();
const open = ref(false);
const tableData = ref([]);
const total = ref(0);
const showSearch = ref(true);
const restock = ref({});
const stockList = ref([]);
const multipleSelection = ref([])
const { proxy } = getCurrentInstance();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  productId: null,
  quantity : null,
  storeId: null
})
const supplying = reactive({
  productId: null,
  storeId: null,
  storeName: null,
});
const type = ref(false);// 声明 `type` 变量

function getStockOptions(row) {
  open.value = true;
  queryParams.quantity = row.quantity;
  queryParams.productName = row.productName;
  queryParams.productId = row.productId;
  queryParams.storeId = row.storeId;
  supplying.productId = row.productId;
  getListStock(queryParams).then(response => {
    stockList.value = response.rows;
    total.value = response.total;
  });
}




function getList(restockId) {
    getStockDetail(restockId).then(response => {
      console.log(type.value);
      tableData.value = response.data.restockProducts;
      restock.value = response.data;
    });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  multipleSelection.value = selection
}

// 格式化函数
function formatPrice(row, property) {
  return `${row[property]}元`;
}

// 取消按钮
function cancel() {
  open.value = false;
  //清空list
  stockList.value = [];
}

function handleDelete(index){
  // 删除指定索引的行
  tableData.value.splice(index, 1)
}


function handleChange(row) {
  row.quantity = row.quantity;
}




/** 开启选择商品 */
function addRow(){
}

function edit(){
  type.value = true;
}

function submitForm(){
 if(multipleSelection.value.length === 0){
   ElMessage.warning('请至少选择一个商品')
   return
 }

  //通过循环遍历，将选中的供货门店id添加到对应的tableData中
  for (let i = 0; i < multipleSelection.value.length; i++) {
    const item = multipleSelection.value[i];
    const index = tableData.value.findIndex(row => row.productId === item.productId);
    if (index !== -1) {
      tableData.value[index].supplyingStoreId = item.storeId;
      tableData.value[index].supplyingStoreName = item.storeName;
    }
  }
  open.value = false;
  stockList.value = [];
}

/** 主表提交审核 */
function submitMainForm(){
  proxy.$refs["refRestockTable"].validate(valid => {
    if (valid) {
      if (tableData.value === null || tableData.value.length === 0) {
        ElMessage.warning('请处理')
        return
      } else {
        console.log(tableData.value)
        restock.value.restockProducts = tableData.value;
        submitRestock(restock.value).then(response => {
          //状态码：200 成功
          if (response.code === 200) {
            ElMessage.success("提交成功");
            proxy.$emit('ok');
            mainCancel();
          }else if (response.code === 500) {
            ElMessage.error(response.msg);
          }
        });
      }
    }
  });
}




/** 重置按钮操作 */
function resetQuery() {
  queryParams.productName = ''
  queryParams.categoryId = null
  handleQuery();
}

/** 主表取消按钮操作 */
function mainCancel() {
  // const obj = { path: "/restock/restock/restock" };
  // proxy.$tab.closeOpenPage(obj);
  proxy.$router.push('/dispatch/dispatch');
}

const {restockId } = route.query;
getList(restockId);

</script>

<style scoped>

.el-input-number--small {
  width: 90px;
  line-height: 22px;
}

</style>